package com.study.manage.mvc.v2;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.study.manage.dal.BlogCommentRepository;
import com.study.manage.dal.BlogGradeRepository;
import com.study.manage.dal.BlogHeartRepository;
import com.study.manage.dal.BlogMediaRepository;
import com.study.manage.dal.BlogRankRepository;
import com.study.manage.dal.BlogRepository;
import com.study.manage.dal.BlogStatDayRepository;
import com.study.manage.dal.EvaluateApplyRepository;
import com.study.manage.dal.EvaluateApplyTeamDetailRepository;
import com.study.manage.dal.EvaluateApplyTeamRepository;
import com.study.manage.dal.EvaluateApplyWorkRepository;
import com.study.manage.dal.EvaluateApplyWorkVoteRepository;
import com.study.manage.dal.EvaluateBrandOrgRecommendRepository;
import com.study.manage.dal.EvaluateGroupDetailRepository;
import com.study.manage.dal.EvaluateJuryRepository;
import com.study.manage.dal.EvaluateNewRepository;
import com.study.manage.dal.EvaluatePriceRepository;
import com.study.manage.dal.EvaluateRepository;
import com.study.manage.dal.EvaluateSingupPoolRepository;
import com.study.manage.dal.EvaluateWinnerRepository;
import com.study.manage.dal.MemoRepository;
import com.study.manage.dal.NewsRepository;
import com.study.manage.dal.OrdersPayRepository;
import com.study.manage.dal.OrdersRepository;
import com.study.manage.dal.UserDetailRepository;
import com.study.manage.dal.UserRepository;
import com.study.manage.domain.Blog;
import com.study.manage.domain.BlogRank;
import com.study.manage.domain.Evaluate;
import com.study.manage.domain.EvaluateApply;
import com.study.manage.domain.EvaluateApplyTeam;
import com.study.manage.domain.EvaluateApplyTeamDetail;
import com.study.manage.domain.EvaluateApplyWork;
import com.study.manage.domain.EvaluateJury;
import com.study.manage.domain.EvaluateNew;
import com.study.manage.domain.EvaluatePrice;
import com.study.manage.domain.Media;
import com.study.manage.domain.Memo;
import com.study.manage.domain.News;
import com.study.manage.domain.Orders;
import com.study.manage.domain.OrdersPay;
import com.study.manage.domain.User;
import com.study.manage.domain.UserDetail;
import com.study.manage.domain.enumm.BlogType;
import com.study.manage.domain.enumm.EAState;
import com.study.manage.domain.enumm.EvaluateApplyType;
import com.study.manage.domain.enumm.EvaluateApplyVerifyState;
import com.study.manage.domain.enumm.EvaluateNewType;
import com.study.manage.domain.enumm.EvaluateVerify;
import com.study.manage.domain.enumm.LiveDieState;
import com.study.manage.domain.enumm.OrdersType;
import com.study.manage.domain.enumm.PayState;
import com.study.manage.domain.enumm.ReleaseState;
import com.study.manage.dto.AjaxResponse;
import com.study.manage.dto.ExcelData;
import com.study.manage.dto.JsonResponseBean;
import com.study.manage.dto.SessionUser;
import com.study.manage.mvc.common.UploadController;
import com.study.manage.mvc.org.judges.JudgesService;
import com.study.manage.redis.RedisRepository;
import com.study.manage.service.DiscountService;
import com.study.manage.service.EvaluateService;
import com.study.manage.utils.CmnStringUtils;
import com.study.manage.utils.DateTimeUtil;
import com.study.manage.utils.ExportExcelUtils;
import com.study.manage.utils.FileUtil;
import com.study.manage.utils.HttpClient;
import com.study.manage.utils.ManageUtils;
import com.study.manage.utils.MapUtils;


@Controller
@RequestMapping("/v2/evaluate")
public class V2EvaluateController extends UploadController {

    @Autowired
    private EvaluateApplyRepository evaluateApplyRepository;
    @Autowired
    private EvaluateRepository evaluateRepository;
    @Autowired
    private BlogRepository blogRepository;
    @Autowired
    private OrdersRepository ordersRepository;
    @Autowired
    private EvaluateService evaluateService;

    @RequestMapping(path = "list", method = RequestMethod.GET)
    public String index(HttpServletRequest request, ModelMap model, HttpServletResponse response) {
        return "v2/evaluate/list";
    }

    @RequestMapping(path = "list-detail", method = RequestMethod.GET)
    public String list_detail(Long id, HttpServletRequest request, ModelMap model,
            HttpServletResponse response) {
        Evaluate source = evaluateRepository.findOne(id);
        Map<String, Object> map = MapUtils.convert(source);
        List<Long> evaluateIds = new ArrayList<>();
        evaluateIds.add(source.id);

        map.put("moneySum", ordersRepository.sumTotalByPayStateAndEvaluateIdInAndDate(PayState.YZF,
                evaluateIds, null));
        if (!StringUtils.isEmpty(source.timeInList)) {
            map.put("timeInList", source.timeInList);
        } else {
            map.put("timeInList",
                    new StringBuilder(DateTimeUtil.format(source.beginAt, "yyyy-MM-dd")).append(" ")
                            .append(DateTimeUtil.format(source.endAt, "yyyy-MM-dd")));
        }
        map.put("originalPrice", source.originalPrice);
        List<String> charges = evaluatePriceRepository.findChargeByEvaluateIdAndState(source.id,
                LiveDieState.LIVE);
        map.put("charge", ManageUtils.getShowPrice(charges));
        model.put("data", map);
        return "v2/evaluate/list-detail";
    }


    @RequestMapping(path = "list-detailApply", method = RequestMethod.GET)
    public String listDetailApply(Long id, HttpServletRequest request, ModelMap model,
            HttpServletResponse response) {
        Evaluate e = evaluateRepository.findOne(id);
        model.put("labels", e.labels);
        return "v2/evaluate/list-detailApply";
    }


    @RequestMapping(path = "list-detailOrder", method = RequestMethod.GET)
    public String listDetailOrder(HttpServletRequest request, ModelMap model,
            HttpServletResponse response) {
        return "v2/evaluate/list-detailOrder";
    }

    @RequestMapping(path = "list-detailPass", method = RequestMethod.GET)
    public String listDetailPass(HttpServletRequest request, Long id,
            @RequestParam(defaultValue = "work") String showType, ModelMap model,
            HttpServletResponse response) {
        Evaluate e = evaluateRepository.findOne(id);
        model.put("labels", e.labels);
        if ("user".equals(showType)) {
            return "v2/evaluate/list-detailPass_user";
        } else {
            return "v2/evaluate/list-detailPass_work";
        }

    }


    @RequestMapping(path = "ref", method = RequestMethod.GET)
    public String listRef(HttpServletRequest request, ModelMap model,
            HttpServletResponse response) {
        return "v2/evaluate/ref";
    }

    @RequestMapping(path = "ref-apply", method = RequestMethod.GET)
    public String refApply(HttpServletRequest request, ModelMap model,
            HttpServletResponse response) {
        return "v2/evaluate/ref-apply";
    }

    @RequestMapping(path = "list-detailNews", method = RequestMethod.GET)
    public String listDetailNews(HttpServletRequest request, ModelMap model,
            HttpServletResponse response) {
        return "v2/evaluate/list-detailNews";
    }


    @ResponseBody
    @RequestMapping(path = "list-detailNewsList", method = RequestMethod.GET)
    public AjaxResponse listDetailNewsList(Long evaluateId, EvaluateNewType type,
            @RequestParam(defaultValue = "LIVE") LiveDieState state,
            @PageableDefault(sort = {"createdAt"}, direction = Direction.DESC) Pageable pageable) {
        AjaxResponse ajax = new AjaxResponse(true);
        Page<EvaluateNew> page =
                evaluateNewRepository.findByEvaluateIdAndTypeAndLive(evaluateId, type, pageable);
        return ajax.setObj(page.map(new Converter<EvaluateNew, Map<String, Object>>() {
            @Override
            public Map<String, Object> convert(EvaluateNew source) {
                News news = newsRepository.findOne(source.newsId);
                Map<String, Object> map = MapUtils.convert(news);
                map.put("stateDesc", news.state.desc);
                map.put("typeDesc", news.type.desc);
                map.put("id", source.id);
                map.put("isTop", source.isTop);
                map.put("linkAt", source.createdAt);
                return map;
            }
        }));
    }

    @Transactional
    @ResponseBody
    @RequestMapping(path = "list-detailNewsSave", method = RequestMethod.POST)
    public AjaxResponse listDetailNewsSave(Long id, HttpServletRequest request) {
        AjaxResponse ajax = new AjaxResponse(true);
        EvaluateNew en = null;
        if (id == null) {
            en = new EvaluateNew();
            MapUtils.copyObj(getRequestParameter(request), en);
        } else {
            en = evaluateNewRepository.findOne(id);
            MapUtils.copyObj(getRequestParameter(request), en, "evaluateId");
        }
        evaluateNewRepository.save(en);
        this.cleanRedisData(new StringBuilder("evaluates:evaluate:").append(en.evaluateId)
                .append(":new:page:10").toString());
        return ajax;
    }


    @Autowired
    private BlogHeartRepository blogHeartRepository;
    @Autowired
    private EvaluateApplyWorkVoteRepository evaluateApplyWorkVoteRepository;
    @Autowired
    private BlogMediaRepository blogMediaRepository;
    @Autowired
    private BlogCommentRepository blogCommentRepository;
    @Autowired
    private BlogGradeRepository blogGradeRepository;

    // 取得作品信息
    private Map<String, Object> getWorkByBlog(Blog source) {
        EvaluateApply ea = evaluateApplyRepository.findOne(source.extId);
        Map<String, Object> map = MapUtils.convert(ea);
        User user = userRepository.findOne(source.userId);
        map.put("imgUrl", qiniuUrl + "pic_avatar_" + user.number + ".jpg");
        map.put("userNumber", user.number);
        map.put("userName", user.name);
        if (ea.referenceId != null) {
            User refUer = userRepository.findOne(ea.referenceId);
            map.put("refName", refUer.name);
            map.put("refId", refUer.number);
        }
        map.put("verifyStateDesc", ea.verifyState.desc);
        map.put("heartCount",
                blogHeartRepository.sumCountByBlogIdAndState(source.id, LiveDieState.LIVE));
        map.put("voteCount", evaluateApplyWorkVoteRepository.sumCountByBlogIdAndState(source.id,
                LiveDieState.LIVE));
        map.put("uploadAt", source.createdAt);
        map.put("text", CmnStringUtils.isEmpty(source.text) ? "" : source.text);
        List<Media> bs = blogMediaRepository.findMediaByBlogId(source.id);
        map.put("bs", bs);
        if (!bs.isEmpty()) {
            map.put("media", bs.get(0));
        }

        map.put("voteCount", evaluateApplyWorkVoteRepository.countByEvaluateApplyIdAndState(ea.id,
                LiveDieState.LIVE));
        map.put("point", "0");
        map.put("juryPoint", "0");
        EvaluateApplyWork eaw =
                evaluateApplyWorkRepository.findByEvaluateApplyIdAndState(ea.id, LiveDieState.LIVE);
        if (eaw != null) {
            map.put("blogId", source.id);
            if (source.id != null) {
                Blog b = blogRepository.findOne(source.id);
                if (b != null && b.extUrl != null) {
                    map.put("point", b.extUrl);
                }
                map.put("likeCount",
                        blogHeartRepository.sumCountByBlogIdAndState(source.id, LiveDieState.LIVE));
                map.put("commentCount",
                        blogCommentRepository.countByBlogIdAndState(source.id, LiveDieState.LIVE));
                Float jury = blogGradeRepository.sumPointByBlogIdAndIsEvaluateJury(source.id, true);
                if (jury != null) {
                    map.put("juryPoint", new DecimalFormat(".0").format(jury));
                }
                map.put("juryCount",
                        blogGradeRepository.countByBlogIdAndIsEvaluateJury(source.id, true));
                Float point =
                        blogGradeRepository.sumPointByBlogIdAndIsEvaluateJury(source.id, null);
                if (point != null) {
                    map.put("point", new DecimalFormat(".0").format(point));
                }
            }
        }
        return map;
    }


    @RequestMapping(path = "list-detailPassInfo", method = RequestMethod.GET)
    public String listDetailPassInfo(HttpServletRequest request, Long evaluateApplyId,
            ModelMap model, HttpServletResponse response) {
        List<Blog> blogs =
                blogRepository.findByTypeAndExtId(BlogType.StudyEvaluate, evaluateApplyId);
        List<Map<String, Object>> lists = new ArrayList<>();
        for (Blog blog : blogs) {
            lists.add(getWorkByBlog(blog));
        }
        model.put("data", jsonMapper.toJson(lists));
        return "v2/evaluate/list-detailPassInfo";

    }

    @Autowired
    private BlogRankRepository blogRankRepository;

    @ResponseBody
    @RequestMapping(path = "list-detailPassWorkList", method = RequestMethod.GET)
    public AjaxResponse listDetailPassWorkList(HttpServletRequest request, Long evaluateId,
            String number, Long userId, String fullName, Long referenceId,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date beginAt,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date endAt, Integer member,
            EvaluateApplyVerifyState verifyState, Pageable pageable) {
        AjaxResponse ajax = new AjaxResponse(true);
        number = StringUtils.isEmpty(number) ? null : number;
        fullName = StringUtils.isEmpty(fullName) ? null : fullName;
        if (userId != null) {
            User u = userRepository.findByNumber(userId);
            if (u != null) {
                userId = u.id;
            }
        }
        if (referenceId != null) {
            User u = userRepository.findByNumber(referenceId);
            if (u != null) {
                referenceId = u.id;
            }
        }
        Page<BlogRank> page = blogRankRepository.findByEvaluateIdInAndState(
                Arrays.asList(evaluateId), LiveDieState.LIVE, number, userId, fullName, referenceId,
                beginAt, endAt, member, pageable);
        return ajax.setObj(page.map(new Converter<BlogRank, Map<String, Object>>() {
            @Override
            public Map<String, Object> convert(BlogRank source) {
                Map<String, Object> map = MapUtils.convert(source);
                User user = userRepository.findById(source.userId);
                map.put("userNumber", user.number);
                map.put("userName", user.name);
                Blog blog = blogRepository.findOne(source.blogId);
                map.put("text", blog.text);
                List<Media> bs = blogMediaRepository.findMediaByBlogId(source.blogId);
                map.put("bs", bs);
                if (!bs.isEmpty()) {
                    map.put("media", bs.get(0));
                }
                EvaluateApply ea = evaluateApplyRepository.findOne(source.evaluateApplyId);
                map.putAll(MapUtils.convert(ea, "remark", "verifyState", "passAt", "phone",
                        "groupName", "itemName", "advName"));
                map.put("applyText", ea.text);

                if (ea.referenceId != null) {
                    User refUer = userRepository.findOne(ea.referenceId);
                    map.put("refName", refUer.name);
                    map.put("refId", refUer.number);
                }

                return map;
            }
        }));
    }

    @Autowired
    private EvaluateWinnerRepository evaluateWinnerRepository;
    @Autowired
    private EvaluateGroupDetailRepository evaluateGroupDetailRepository;

    @ResponseBody
    @RequestMapping(path = "list-detailPassWorkVerify", method = RequestMethod.POST)
    public AjaxResponse listDetailPassWorkVerify(HttpServletRequest request, Long id,
            EvaluateApplyVerifyState verifyState, Pageable pageable) {
        AjaxResponse ajax = new AjaxResponse(true);
        EvaluateApply ea = evaluateApplyRepository.findOne(id);
        if (ea.verifyState != EvaluateApplyVerifyState.JJ && verifyState != null) {
            if (verifyState == EvaluateApplyVerifyState.JJ) {
                Map<String, Object> map = new HashMap<>();
                map.put("evaluateApplyId", ea.id);
                return HttpClient.post(serverUrl + "/admin/evaluateApplyRank", map);
            } else {
                ea.verifyState = verifyState;
                evaluateApplyRepository.save(ea);
            }
        }
        return ajax;
    }


    @ResponseBody
    @RequestMapping(path = "list-detailPassWorkRemark", method = RequestMethod.POST)
    public AjaxResponse listDetailPassWorkRemark(HttpServletRequest request, Long id, String msg,
            Pageable pageable) {
        AjaxResponse ajax = new AjaxResponse(true);
        EvaluateApply ea = evaluateApplyRepository.findOne(id);
        ea.remark = msg;
        evaluateApplyRepository.save(ea);
        return ajax;
    }

    @ResponseBody
    @RequestMapping(path = "list-list", method = RequestMethod.GET)
    public AjaxResponse listList(ReleaseState state,
            @PageableDefault(sort = {"createdAt"}, direction = Direction.DESC) Pageable pageable) {
        AjaxResponse ajax = new AjaxResponse(true);
        SessionUser su = this.getUserInfo();
        Page<Evaluate> page = evaluateRepository.findByUserIdAndState(su.getId(), state, pageable);
        return ajax.setObj(page.map(new Converter<Evaluate, Map<String, Object>>() {
            @Override
            public Map<String, Object> convert(Evaluate source) {
                Map<String, Object> map = MapUtils.convert(source);
                map.put("stateDesc", source.state.desc);
                List<Long> evaluateIds = new ArrayList<>();
                evaluateIds.add(source.id);
                map.put("applyCount", evaluateApplyRepository.countByEvaluateIdInAndVerifyAndState(
                        evaluateIds, EvaluateVerify.Pass, EAState.LIVE));

                map.put("moneySum", ordersRepository
                        .sumTotalByPayStateAndEvaluateIdInAndDate(PayState.YZF, evaluateIds, null));
                if (!StringUtils.isEmpty(source.timeInList)) {
                    map.put("timeInList", source.timeInList);
                } else {
                    map.put("timeInList",
                            new StringBuilder(DateTimeUtil.format(source.beginAt, "yyyy-MM-dd"))
                                    .append(" ").append(
                                            DateTimeUtil.format(source.endAt, "yyyy-MM-dd")));
                }
                map.put("originalPrice", source.originalPrice);
                List<String> charges = evaluatePriceRepository
                        .findChargeByEvaluateIdAndState(source.id, LiveDieState.LIVE);
                map.put("charge", ManageUtils.getShowPrice(charges));
                return map;
            }

        }));
    }

    @Autowired
    private EvaluatePriceRepository evaluatePriceRepository;
    @Autowired
    private UserRepository userRepository;


    @ResponseBody
    @RequestMapping(path = "list-count", method = RequestMethod.GET)
    public AjaxResponse listCount(Long evaluateId, ReleaseState state) {
        AjaxResponse ajax = new AjaxResponse(true);
        SessionUser su = this.getUserInfo();
        return ajax.setObj(evaluateService.statCount(su.getId(), evaluateId, state));
    }

    @Autowired
    private EvaluateApplyWorkRepository evaluateApplyWorkRepository;
    @Autowired
    private BlogStatDayRepository blogStatDayRepository;

    @ResponseBody
    @RequestMapping(path = "list-detailStat", method = RequestMethod.GET)
    public AjaxResponse listDetailStat(@DateTimeFormat(pattern = "yyyy-MM-dd") Date beginAt,
            @RequestParam(defaultValue = "BM") String type,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date endAt, Long id) {
        AjaxResponse ajax = new AjaxResponse(true);
        return ajax.setObj(evaluateService.listStatCount(id, null, type, beginAt, endAt));
    }


    @RequestMapping(path = "list-detailStatExport", method = RequestMethod.GET)
    public void listDetailStatExport(@DateTimeFormat(pattern = "yyyy-MM-dd") Date beginAt,
            @RequestParam(defaultValue = "BM") String type,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date endAt, Long id) throws Exception {
        List<String> arra = new ArrayList<>();
        String fileName = null;
        if ("BM".equals(type)) {
            arra.add("报名人数（提交）");
            arra.add("报名过审人数");
            arra.add("报名成功人数");
            arra.add("报名收费");
            arra.add("已拒绝");
            arra.add("待审核");
            fileName = "报名人数";
        } else if ("ZP".equals(type)) {
            arra.add("作品帖数（所有）");
            arra.add("作品帖数（最终）");
            arra.add("评委点评作品数");
            arra.add("评委打分作品数");
            fileName = "作品帖数";
        } else if ("SF".equals(type)) {
            arra.add("报名收费");
            arra.add("报名成功人数");
            arra.add("商品售卖数");
            arra.add("商品收费");
            arra.add("投票数");
            arra.add("投票收费");
            fileName = "收费量";
        } else if ("LL".equals(type)) {
            arra.add("帖子浏览数");
            fileName = "浏览量";
        } else if ("DK".equals(type)) {
            arra.add("帖子打开数");
            fileName = "打开量";
        } else if ("HD".equals(type)) {
            arra.add("互动总数");
            arra.add("点赞数量");
            arra.add("打分数量");
            arra.add("点评数量");
            arra.add("讨论数量");
            arra.add("投票数量");
            fileName = "互动量";
        }
        List<Map<String, Object>> list =
                evaluateService.listStatCount(id, null, type, beginAt, endAt);
        StringBuilder sb = new StringBuilder("日期");
        for (String title : arra) {
            sb.append(",").append(title);
        }
        sb.append("\n");
        for (Map<String, Object> map : list) {
            sb.append(map.containsKey("date") ? map.get("date") : "");
            for (String title : arra) {
                sb.append(",").append(map.containsKey(title)
                        ? map.get(title).toString().replace(".00", "") : "0");
            }
            sb.append("\n");
        }
        this.export(fileName, sb.toString(), response);
    }

    @Autowired
    private MemoRepository memoRepository;

    @ResponseBody
    @RequestMapping(path = "list-detailDemo", method = RequestMethod.GET)
    public AjaxResponse listDetailMemo(Long evaluateId,
            @PageableDefault(sort = {"createdAt"}, direction = Direction.DESC) Pageable pageable) {
        AjaxResponse ajax = new AjaxResponse(true);
        List<Long> evaluateIds = new ArrayList<>(Arrays.asList(evaluateId));
        Page<Memo> page = memoRepository.findByEvaluateIdIn(evaluateIds, pageable);
        return ajax.setObj(page);
    }


    @ResponseBody
    @RequestMapping(path = "list-detailMemoSave", method = RequestMethod.GET)
    public AjaxResponse listDetailMemoSave(Long id) {
        AjaxResponse ajax = new AjaxResponse(true);
        Memo memo = null;
        if (id == null) {
            memo = new Memo();
            SessionUser su = this.getUserInfo();
            memo.userId = su.getId();
        } else {
            memo = memoRepository.findOne(id);
        }
        MapUtils.copyProperties(memo, getRequestParameter(request));
        memoRepository.save(memo);
        return ajax;
    }

    @Autowired
    private EvaluateNewRepository evaluateNewRepository;
    @Autowired
    private NewsRepository newsRepository;

    @ResponseBody
    @RequestMapping(path = "list-detailNew", method = RequestMethod.GET)
    public AjaxResponse listDetailNew(HttpServletRequest request,
            @RequestParam(defaultValue = "ZT") EvaluateNewType type, Long evaluateId,
            @PageableDefault(sort = {"createdAt"}, direction = Direction.DESC) Pageable pageable) {
        AjaxResponse ajax = new AjaxResponse(true);
        SessionUser su = this.getUserInfo();
        Page<News> page = newsRepository.findByTypeInAndUserIdAndEvaluateId(Arrays.asList(type),
                su.getId(), evaluateId, pageable);
        return ajax.setObj(page);
    }

    @Autowired
    private EvaluateSingupPoolRepository evaluateSingupPoolRepository;

    @ResponseBody
    @RequestMapping(path = "list-detailYunYing", method = RequestMethod.GET)
    public AjaxResponse listDetailYunYing(Long evaluateId) {

        AjaxResponse ajax = new AjaxResponse(true);
        List<Long> evaluateIds = new ArrayList<>(Arrays.asList(evaluateId));
        Map<String, Object> map = new HashMap<>();
        map.put("applyCount", evaluateApplyRepository.countByEvaluateIdInAndVerifyAndStateAndDate(
                evaluateIds, EvaluateVerify.Pass, EAState.LIVE, null));
        map.put("blogCount",
                evaluateApplyWorkRepository.countByEvaluateIdInAndDay(evaluateIds, null));
        map.put("jjCount", evaluateApplyRepository.countByIdAndVerifyAndVerifyState(evaluateId,
                null, EvaluateApplyVerifyState.JJ));
        map.put("hxCount", evaluateSingupPoolRepository.countByEvaluateIdAndState(evaluateId,
                LiveDieState.LIVE));

        List<OrdersType> ordersTypes = new ArrayList<>();
        ordersTypes.add(OrdersType.BSBM);
        ordersTypes.add(OrdersType.TTBSBM);
        map.put("totalPrice", ordersRepository.sumTotalByPayStateAndEvaluateIdInAndTypeAndDate(
                PayState.YZF, evaluateIds, ordersTypes, null));
        ordersTypes.clear();
        ordersTypes.add(OrdersType.SP);
        map.put("otherTotalPrice", ordersRepository.sumTotalByPayStateAndEvaluateIdInAndTypeAndDate(
                PayState.YZF, evaluateIds, ordersTypes, null));

        map.put("juryCount",
                EvaluateJuryRepository.countByEvaluateIdAndState(evaluateId, LiveDieState.LIVE));
        return ajax.setObj(map);
    }

    @Autowired
    private EvaluateJuryRepository EvaluateJuryRepository;

    @ResponseBody
    @RequestMapping(path = "list-detailApplyStatCount", method = RequestMethod.GET)
    public AjaxResponse listDetailApplyStat(Long evaluateId) {

        AjaxResponse ajax = new AjaxResponse(true);
        Date date = new Date();
        List<Long> es = Arrays.asList(evaluateId);

        Map<String, Object> map = new HashMap<>();
        map.put("bmCount", evaluateApplyRepository.countByEvaluateIdInAndVerifyInAndStateInAndDate(
                es, Arrays.asList(EvaluateVerify.values()),
                Arrays.asList(EAState.LIVE, EAState.UNPAID, EAState.FREEWAITINGVERIFY), null));
        map.put("bmCountDay",
                evaluateApplyRepository.countByEvaluateIdInAndVerifyInAndStateInAndDate(es,
                        Arrays.asList(EvaluateVerify.values()), Arrays.asList(EAState.LIVE,
                                EAState.UNPAID, EAState.FREEWAITINGVERIFY),
                        date));
        map.put("successCount",
                evaluateApplyRepository.countByEvaluateIdInAndVerifyInAndStateInAndDate(es,
                        Arrays.asList(EvaluateVerify.Pass), Arrays.asList(EAState.LIVE), null));
        map.put("successCountDay",
                evaluateApplyRepository.countByEvaluateIdInAndVerifyInAndStateInAndDate(es,
                        Arrays.asList(EvaluateVerify.Pass), Arrays.asList(EAState.LIVE), date));
        map.put("passCount",
                evaluateApplyRepository.countByEvaluateIdInAndVerifyInAndStateInAndDate(es,
                        Arrays.asList(EvaluateVerify.Pass),
                        Arrays.asList(EAState.LIVE, EAState.UNPAID), null));
        map.put("passCountDay",
                evaluateApplyRepository.countByEvaluateIdInAndVerifyInAndStateInAndDate(es,
                        Arrays.asList(EvaluateVerify.Pass),
                        Arrays.asList(EAState.LIVE, EAState.UNPAID), date));
        map.put("waitCount",
                evaluateApplyRepository.countByEvaluateIdInAndVerifyInAndStateInAndDate(es,
                        Arrays.asList(EvaluateVerify.Waiting),
                        Arrays.asList(EAState.LIVE, EAState.UNPAID), null));
        map.put("waitCountDay",
                evaluateApplyRepository.countByEvaluateIdInAndVerifyInAndStateInAndDate(es,
                        Arrays.asList(EvaluateVerify.Waiting),
                        Arrays.asList(EAState.LIVE, EAState.UNPAID), date));
        map.put("workApplyCount", evaluateApplyWorkRepository.countByEvaluateIdInAndDay(es, null));
        map.put("workApplyCountDay",
                evaluateApplyWorkRepository.countByEvaluateIdInAndDay(es, date));

        map.put("orderSum", ordersRepository.sumTotalByPayStateAndEvaluateIdInAndTypeAndDate(
                PayState.YZF, es, Arrays.asList(OrdersType.BSBM, OrdersType.TTBSBM), null));
        map.put("orderSumDay", ordersRepository.sumTotalByPayStateAndEvaluateIdInAndTypeAndDate(
                PayState.YZF, es, Arrays.asList(OrdersType.BSBM, OrdersType.TTBSBM), date));
        return ajax.setObj(map);
    }


    @ResponseBody
    @RequestMapping(path = "list-detailApplyList", method = RequestMethod.GET)
    public AjaxResponse listDetailApplyList(Long evaluateId, String name, EvaluateVerify verify,
            EAState state, @DateTimeFormat(pattern = "yyyy-MM-dd") Date beginAt,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date endAt,
            @PageableDefault(sort = {"createdAt"}, direction = Direction.DESC) Pageable pageable) {
        Long userId = null;
        if (!StringUtils.isEmpty(name)) {
            if (NumberUtils.isNumber(name)) {
                Long number = Long.valueOf(name);
                User u = userRepository.findByNumber(number);
                if (u != null) {
                    userId = u.id;
                    name = null;
                }

            }
        } else {
            name = null;
        }

        AjaxResponse ajax = new AjaxResponse(true);
        Page<EvaluateApply> page = evaluateApplyRepository.findEvaluateApplys(evaluateId, beginAt,
                endAt, name, userId, verify, state, null, pageable);
        return ajax.setObj(page.map(new Converter<EvaluateApply, Map<String, Object>>() {
            @Override
            public Map<String, Object> convert(EvaluateApply source) {
                Map<String, Object> map = MapUtils.convert(source);
                User user = userRepository.findOne(source.userId);
                map.put("userNumber", user.number);
                map.put("userName", user.name);
                map.put("typeDesc", source.type.desc);
                if (source.verify != null)
                    map.put("verifyDesc", source.verify.desc);
                map.put("stateDesc", source.state.desc);
                if (source.referenceId != null) {
                    User refUer = userRepository.findOne(source.referenceId);
                    String refName = "";
                    if (refUer != null) {
                        UserDetail ud = userDetailRepository.findByUserId(refUer.id);
                        refName = refUer.name + "（" + ud.realName + "）";
                    }
                    map.put("refName", refName);
                    map.put("refId", refUer.number);
                } else {
                    map.put("refName", "--");
                }
                if (source.evaluatePriceId != null) {
                    EvaluatePrice ep = evaluatePriceRepository.findOne(source.evaluatePriceId);
                    map.put("epName", ep.title + "(" + ep.charge + ")");
                } else {
                    map.put("epName", "--");
                }
                map.put("verifyDesc", source.verify.desc);
                map.put("verifyStateDesc", source.verifyState.desc);
                map.put("stateDesc", source.state.desc);
                List<EvaluateApplyWork> eaws = evaluateApplyWorkRepository
                        .findByEvaluateApplyIdAndUserIdAndState(source.id, source.userId, LiveDieState.LIVE);

                if (eaws.isEmpty()) {
                    map.put("firstUploadAt", "");
                    map.put("hasWork", "无");
                } else {
                    map.put("firstUploadAt", eaws.get(0).createdAt);
                    map.put("hasWork", "有");
                }

                map.put("payStateDesc", "待支付");
                if (source.type == EvaluateApplyType.TEAM) {
                    map.put("orderItemPrice",
                            evaluateApplyTeamRepository.sumMoneyByApplyId(source.id));
                } else {
                    List<Orders> os =
                            ordersRepository.findByTypeAndExtId(OrdersType.BSBM, source.id);
                    if (!os.isEmpty()) {
                        map.put("orderItemPrice", os.get(0).total);
                        map.put("orderNo", os.get(0).orderNo);
                        map.put("payStateDesc", os.get(0).payState.desc);
                    }
                }
                return map;
            }
        }));
    }

    @Autowired
    private DiscountService discountService;
    @Autowired
    private RedisRepository redisRepository;

    @ResponseBody
    @RequestMapping(path = "list-detailApplyRemark", method = RequestMethod.POST)
    public AjaxResponse list_detailApplyVerify(Long id, String remark) {
        EvaluateApply ea = evaluateApplyRepository.findOne(id);
        ea.remark = remark;
        evaluateApplyRepository.save(ea);
        return new AjaxResponse(true);
    }

    @ResponseBody
    @RequestMapping(path = "list-detailApplyVerify", method = RequestMethod.POST)
    public AjaxResponse list_detailApplyVerify(Long id, EvaluateVerify verify) {
        // EvaluateApply ea = evaluateApplyRepository.findOne(id);
        if (verify != null) {

            Map<String, Object> map = new HashMap<>();
            map.put("evaluateApplyId", id);
            map.put("verify", verify);
            map.put("msg", "");
            return HttpClient.post(serverUrl + "/admin/evaluateApplyVerify", map);

            // ea.verify = verify;
            // evaluateApplyRepository.save(ea);
        }
        // if (ea.state == EAState.LIVE && ea.verify == EvaluateVerify.Pass) {
        // discountService.discountUser(DiscountType.Evaluate, ea.evaluateId, ea.userId, ea.id);
        // if (ea.evaluatePriceId != null) {
        // discountService.discountUser(DiscountType.EvaluatePrice, ea.evaluatePriceId,
        // ea.userId, ea.id);
        // }
        // }
        return new AjaxResponse(true);
    }

    @Autowired
    private EvaluateApplyTeamRepository evaluateApplyTeamRepository;
    @Autowired
    private EvaluateApplyTeamDetailRepository evaluateApplyTeamDetailRepository;

    @RequestMapping(path = "list-detailApplyExportExecl", method = RequestMethod.GET)
    public void list_applyExport(Long id, @DateTimeFormat(pattern = "yyyy-MM-dd") Date beginAt,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date endAt, HttpServletResponse response)
            throws Exception {
        StringBuilder sb = new StringBuilder();
        Evaluate evaluate = evaluateRepository.findOne(id);
        String[] lables = converLabels(evaluate.labels);
        String[] teamLables = converLabels(evaluate.teamLabels);
        String[] parentLables = converLabels(evaluate.parentInfoLabels);
        List<Object> list = new ArrayList<>();
        list.add("报名时间");
        list.add("首次上传时间");
        list.add("参赛编号");
        list.add("用户");
        list.add("用户ID");
        list.add("报名类型");
        list.add("节目");
        list.add("姓名");
        list.add("电话");
        list.add("组别");
        list.add("渠道");
        list.add("渠道经营者");
        list.add("审核状态");
        list.add("晋级状态");
        list.add("报名状态");
        list.add("付款状态");
        list.add("订单编号");
        list.add("票种");
        list.add("付款");
        list.add("作品");
        list.add("备注");
        list.add(evaluate.applyGroupAdv == null ? "" : evaluate.applyGroupAdv);

        for (String lable : teamLables) {
            list.add(lable);
        }
        for (String lable : lables) {
            list.add(lable);
        }
        for (String parentLable : parentLables) {
            list.add(parentLable);
        }
        sb.append(listToCsvString(list));
        if (beginAt == null) {
            beginAt = evaluate.beginAt;
        }
        if (endAt == null) {
            endAt = evaluate.endAt;
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(beginAt);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        while (cal.getTime().getTime() <= endAt.getTime()) {
            sb.append(list_applyExportDay(cal.getTime(), id, false));
            cal.add(Calendar.DAY_OF_MONTH, 1);
        }
        this.export(evaluate.title + "_报名", sb.toString(), response);
        // ExportExcelUtils.exportExcel(response, evaluate.title + "_报名", excel);
    }

    private String listToCsvString(List<Object> list) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            Object o = list.get(i);
            if (o == null) {
                o = "";
            }
            if (i == 0) {
                sb.append(o.toString().replaceAll(",", "，").replaceAll("\n", " ").replaceAll("\"",
                        " "));
            } else {
                sb.append(",").append(o.toString().replaceAll(",", "，").replaceAll("\n", " ")
                        .replaceAll("\"", " "));
            }
        }
        sb.append("\n");
        return sb.toString();
    }

    public String list_applyExportDay(Date date, Long id, boolean update) {
        Evaluate evaluate = evaluateRepository.findOne(id);
        String[] lables = converLabels(evaluate.labels);
        String[] teamLables = converLabels(evaluate.teamLabels);
        String[] parentLables = converLabels(evaluate.parentInfoLabels);
        StringBuilder sb = new StringBuilder();
        String path = filePath + "csv/" + id + "_" + DateTimeUtil.format(date, "yyyyMMdd") + ".csv";
        if (new File(path).exists() && !update) {
            List<String> list = FileUtil.readData(path);
            for (String st : list) {
                if (!StringUtils.isEmpty(st)) {
                    sb.append(st).append("\n");
                }

            }
            return sb.toString();
        }

        Pageable pageable = new PageRequest(0, 200);
        Page<EvaluateApply> page = null;
        do {
            page = evaluateApplyRepository.findByEvaluateIdAndNotDraftAndDay(id, null, date,
                    pageable);
            List<EvaluateApply> evaluateApplys = page.getContent();
            for (EvaluateApply apply : evaluateApplys) {

                List<Object> arra = redisRepository.excelApplyById(apply.id.toString());
                coverApplyString(arra, teamLables, apply.text, lables, apply.text, parentLables,
                        apply.parentText);

                sb.append(listToCsvString(arra));
                if (apply.type == EvaluateApplyType.TEAM) {
                    List<EvaluateApplyTeam> eats = evaluateApplyTeamRepository
                            .findByEvaluateApplyIdAndState(apply.id, LiveDieState.LIVE);

                    for (EvaluateApplyTeam eat : eats) {
                        List<Orders> teamOs =
                                ordersRepository.findByTypeAndExtId(OrdersType.TTBSBM, eat.id);
                        PayState payStateTeam = PayState.DZF;
                        Float payMoneyTeam = 0f;
                        String orderNoTeam = "--";
                        if (!teamOs.isEmpty()) {
                            payStateTeam = teamOs.get(0).payState;
                            payMoneyTeam = teamOs.get(0).total;
                            orderNoTeam = teamOs.get(0).orderNo;
                        }
                        List<EvaluateApplyTeamDetail> eatds = evaluateApplyTeamDetailRepository
                                .findByEvaluateApplyTeamIdAndState(eat.id, LiveDieState.LIVE);

                        for (int i = 0; i < eatds.size(); i++) {
                            EvaluateApplyTeamDetail eatd = eatds.get(i);

                            List<Object> arra2 = new ArrayList<>();
                            arra2.add("");
                            arra2.add("");
                            arra2.add("");
                            arra2.add("");
                            arra2.add("");
                            arra2.add("");
                            arra2.add(apply.itemName == null ? "" : apply.itemName);
                            arra2.add(apply.fullName == null ? "" : apply.fullName);
                            arra2.add(apply.phone == null ? "" : apply.phone);
                            arra2.add(apply.groupName == null ? "" : apply.groupName);
                            arra2.add("");
                            arra2.add(eat.verify.desc);
                            arra2.add("--");
                            arra2.add("--");
                            arra2.add(payStateTeam.desc);
                            arra2.add(i == 0 ? orderNoTeam : "");
                            arra2.add("");
                            arra2.add(i == 0 ? payMoneyTeam : "");
                            arra2.add("");
                            arra2.add("");
                            arra2.add("");
                            if (i == 0) {
                            } else {
                                coverApplyString(arra2, teamLables, null, lables, eatd.text,
                                        parentLables, null);
                            }
                            sb.append(listToCsvString(arra2));
                        }
                    }
                }

            }
            pageable = new PageRequest(page.getNumber() + 1, page.getSize());
        } while (page.getTotalPages() != page.getNumber());

        if (Integer.valueOf(DateTimeUtil.format(date, "yyyyMMdd")) < Integer
                .valueOf(DateTimeUtil.format(new Date(), "yyyyMMdd"))
                && !sb.toString().equals("")) {
            FileUtil.writeData(sb.toString(), path);
        }
        return sb.toString();
    }



    @SuppressWarnings("unchecked")
    private String[] converLabels(String labelsJson) {
        String[] lables = new String[0];
        List<Map<String, Object>> ls = jsonMapper.fromJson(labelsJson, List.class);
        if (ls != null) {
            lables = new String[ls.size()];
            for (int i = 0; i < ls.size(); i++) {
                Map<String, Object> l = ls.get(i);
                lables[i] = l.get("name").toString();
            }
        } else {
            if (!StringUtils.isEmpty(labelsJson)) {
                lables = labelsJson.split(",");
            }
        }
        return lables;
    }

    @SuppressWarnings("unchecked")
    private void coverApplyString(StringBuilder context, String[] teamLables, String teamText,
            String[] lables, String text, String[] parentLables, String parantText) {
        Map<String, Object> textMap = jsonMapper.fromJson(teamText, Map.class);
        if (textMap == null) {
            textMap = new HashMap<>();
        }
        for (String lable : teamLables) {
            String va = (String) textMap.get(lable);
            context.append(",").append(va == null ? "" : va.replace(",", "，"));
        }
        textMap = jsonMapper.fromJson(text, Map.class);
        if (textMap == null) {
            textMap = new HashMap<>();
        }
        for (String lable : lables) {
            String va = (String) textMap.get(lable);
            context.append(",").append(va == null ? "" : va.replace(",", "，"));
        }
        textMap = jsonMapper.fromJson(parantText, Map.class);
        if (textMap == null) {
            textMap = new HashMap<>();
        }
        for (String parentLable : parentLables) {
            String va = (String) textMap.get(parentLable);
            context.append(",").append(va == null ? "" : va.replace(",", "，"));
        }
    }

    private void coverApplyString(List<Object> context, String[] teamLables, String teamText,
            String[] lables, String text, String[] parentLables, String parantText) {
        Map<String, Object> textMap = jsonMapper.fromJson(teamText, Map.class);
        if (textMap == null) {
            textMap = new HashMap<>();
        }
        for (String lable : teamLables) {
            String va = (String) textMap.get(lable);
            context.add(va == null ? "" : va.replace(",", "，"));
        }
        textMap = jsonMapper.fromJson(text, Map.class);
        if (textMap == null) {
            textMap = new HashMap<>();
        }
        for (String lable : lables) {
            String va = (String) textMap.get(lable);
            context.add(va == null ? "" : va.replace(",", "，"));
        }
        textMap = jsonMapper.fromJson(parantText, Map.class);
        if (textMap == null) {
            textMap = new HashMap<>();
        }
        for (String parentLable : parentLables) {
            String va = (String) textMap.get(parentLable);
            context.add(va == null ? "" : va.replace(",", "，"));
        }
    }

    @Autowired
    private OrdersPayRepository ordersPayRepository;

    @ResponseBody
    @RequestMapping(path = "list-detailOrderList", method = RequestMethod.GET)
    public AjaxResponse listDetailOrderList(Long evaluateId, String name,
            @RequestParam(defaultValue = "BSBM") OrdersType type, EAState state,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date beginAt,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date endAt,
            @PageableDefault(sort = {"payAt"}, direction = Direction.DESC) Pageable pageable) {

        AjaxResponse ajax = new AjaxResponse(true);

        Page<Orders> page = ordersRepository.findByEvaluateIdAndPayStateAndOrderNoAndDate(
                evaluateId, PayState.YZF, null, beginAt, endAt, pageable);
        return ajax.setObj(page.map(new Converter<Orders, Map<String, Object>>() {
            @Override
            public Map<String, Object> convert(Orders source) {
                Map<String, Object> map = MapUtils.convert(source);
                User user = userRepository.findOne(source.userId);
                map.put("userNumber", user.number);
                map.put("userName", user.name);
                map.put("typeDesc", source.type.desc);
                map.put("payStateDesc", source.payState.desc);
                List<OrdersPay> ops = ordersPayRepository.findByOrdersId(source.id);
                for (OrdersPay op : ops) {
                    if (op.state == PayState.YZF) {
                        map.put("tradeType", op.tradeType.desc);
                        map.put("tradeTypeExt", op.tradeTypeExt);
                        map.put("outTradeNo", op.outTradeNo);
                    }
                }
                return map;
            }
        }));
    }



    @ResponseBody
    @RequestMapping(path = "list-detailOrderStatCount", method = RequestMethod.GET)
    public AjaxResponse listDetailOrderStat(Long evaluateId) {

        AjaxResponse ajax = new AjaxResponse(true);
        Date date = new Date();
        List<Long> es = Arrays.asList(evaluateId);

        Map<String, Object> map = new HashMap<>();

        map.put("bsbmSum", ordersRepository.sumTotalByPayStateAndEvaluateIdInAndTypeAndDate(
                PayState.YZF, es, Arrays.asList(OrdersType.BSBM, OrdersType.TTBSBM), null));
        map.put("bsbmSumDay", ordersRepository.sumTotalByPayStateAndEvaluateIdInAndTypeAndDate(
                PayState.YZF, es, Arrays.asList(OrdersType.BSBM, OrdersType.TTBSBM), date));

        map.put("spSum", ordersRepository.sumTotalByPayStateAndEvaluateIdInAndTypeAndDate(
                PayState.YZF, es, Arrays.asList(OrdersType.SP), null));
        map.put("spSumDay", ordersRepository.sumTotalByPayStateAndEvaluateIdInAndTypeAndDate(
                PayState.YZF, es, Arrays.asList(OrdersType.SP), date));

        map.put("bstpSum", ordersRepository.sumTotalByPayStateAndEvaluateIdInAndTypeAndDate(
                PayState.YZF, es, Arrays.asList(OrdersType.BSTP), null));
        map.put("bstpSumDay", ordersRepository.sumTotalByPayStateAndEvaluateIdInAndTypeAndDate(
                PayState.YZF, es, Arrays.asList(OrdersType.BSTP), date));


        return ajax.setObj(map);
    }



    @ResponseBody
    @RequestMapping(path = "list-detailPassStatCount", method = RequestMethod.GET)
    public AjaxResponse listDetailPassStat(Long evaluateId) {

        AjaxResponse ajax = new AjaxResponse(true);
        Date date = new Date();
        List<Long> es = Arrays.asList(evaluateId);

        Map<String, Object> map = new HashMap<>();
        map.put("bmCount", evaluateApplyRepository.countByEvaluateIdInAndVerifyInAndStateInAndDate(
                es, Arrays.asList(EvaluateVerify.Pass), Arrays.asList(EAState.LIVE), null));
        map.put("bmCountDay",
                evaluateApplyRepository.countByEvaluateIdInAndVerifyInAndStateInAndDate(es,
                        Arrays.asList(EvaluateVerify.Pass), Arrays.asList(EAState.LIVE), date));
        map.put("waitCount",
                evaluateApplyRepository
                        .countByEvaluateIdInAndVerifyInAndStateInAndVerifyStateAndDate(es,
                                Arrays.asList(EvaluateVerify.Pass), Arrays.asList(EAState.LIVE),
                                EvaluateApplyVerifyState.DD, null));
        map.put("waitCountDay",
                evaluateApplyRepository
                        .countByEvaluateIdInAndVerifyInAndStateInAndVerifyStateAndDate(es,
                                Arrays.asList(EvaluateVerify.Pass), Arrays.asList(EAState.LIVE),
                                EvaluateApplyVerifyState.DD, date));
        map.put("passCount",
                evaluateApplyRepository
                        .countByEvaluateIdInAndVerifyInAndStateInAndVerifyStateAndDate(es,
                                Arrays.asList(EvaluateVerify.Pass), Arrays.asList(EAState.LIVE),
                                EvaluateApplyVerifyState.JJ, null));
        map.put("passCountDay",
                evaluateApplyRepository
                        .countByEvaluateIdInAndVerifyInAndStateInAndVerifyStateAndDate(es,
                                Arrays.asList(EvaluateVerify.Pass), Arrays.asList(EAState.LIVE),
                                EvaluateApplyVerifyState.JJ, date));
        return ajax.setObj(map);
    }


    @ResponseBody
    @RequestMapping(path = "list-detailPassList", method = RequestMethod.GET)
    public AjaxResponse listDetailPassList(Long evaluateId, String name,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date beginAt,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date endAt,
            @PageableDefault(sort = {"createdAt"}, direction = Direction.DESC) Pageable pageable) {

        AjaxResponse ajax = new AjaxResponse(true);
        Page<EvaluateApply> page = evaluateApplyRepository.findEvaluateApplys(evaluateId, beginAt,
                endAt, name, EvaluateVerify.Pass, EAState.LIVE, null, pageable);
        return ajax.setObj(page.map(new Converter<EvaluateApply, Map<String, Object>>() {
            @Override
            public Map<String, Object> convert(EvaluateApply source) {
                Map<String, Object> map = MapUtils.convert(source);
                User user = userRepository.findOne(source.userId);
                map.put("userNumber", user.number);
                map.put("userName", user.name);
                map.put("typeDesc", source.type.desc);
                if (source.verify != null)
                    map.put("verifyDesc", source.verify.desc);
                if (source.verifyState != null)
                    map.put("verifyStateDesc", source.verifyState.desc);
                map.put("stateDesc", source.state.desc);
                if (source.referenceId != null) {
                    User refUer = userRepository.findOne(source.referenceId);
                    String refName = "";
                    if (refUer != null) {
                        UserDetail ud = userDetailRepository.findByUserId(refUer.id);
                        refName = refUer.name + "（" + ud.realName + "）";
                    }
                    map.put("refName", refName);
                } else {
                    map.put("refName", "--");
                }
                if (source.evaluatePriceId != null) {
                    EvaluatePrice ep = evaluatePriceRepository.findOne(source.evaluatePriceId);
                    map.put("epName", ep.title + "(" + ep.charge + ")");
                } else {
                    map.put("epName", "--");
                }
                return map;
            }
        }));
    }

    @Autowired
    private EvaluateBrandOrgRecommendRepository evaluateBrandOrgRecommendRepository;

    @ResponseBody
    @RequestMapping(path = "ref-list", method = RequestMethod.GET)
    public AjaxResponse refList(ReleaseState state, Pageable pageable) {
        AjaxResponse ajax = new AjaxResponse(true);
        SessionUser su = this.getUserInfo();
        List<Long> ids = new ArrayList<>();
        if (su.getParentId().longValue() == su.getId()) {
            ids = userRepository.findIdByParentIdAndState(su.getId(), LiveDieState.LIVE);
        }
        ids.add(su.getId());
        List<Long> ids2 = ids;
        Page<Evaluate> page = evaluateBrandOrgRecommendRepository
                .findEvaluateByUserIdInAndState(ids, LiveDieState.LIVE, pageable);
        return ajax.setObj(page.map(new Converter<Evaluate, Map<String, Object>>() {
            @Override
            public Map<String, Object> convert(Evaluate source) {
                Map<String, Object> map = MapUtils.convert(source);
                map.put("stateDesc", source.state.desc);
                List<Long> evaluateIds = new ArrayList<>();
                evaluateIds.add(source.id);
                map.put("applyCount",
                        evaluateApplyRepository
                                .countByEvaluateIdInAndReferenceIdAndVerifyInAndStateInAndDate(
                                        evaluateIds, ids2, Arrays.asList(EvaluateVerify.Pass),
                                        Arrays.asList(EAState.LIVE), null));

                map.put("moneySum", ordersRepository
                        .sumTotalByPayStateAndEvaluateIdInAndDate(PayState.YZF, evaluateIds, null));
                if (!StringUtils.isEmpty(source.timeInList)) {
                    map.put("timeInList", source.timeInList);
                } else {
                    map.put("timeInList",
                            new StringBuilder(DateTimeUtil.format(source.beginAt, "yyyy-MM-dd"))
                                    .append(" ").append(
                                            DateTimeUtil.format(source.endAt, "yyyy-MM-dd")));
                }
                if (source.userId != null) {
                    User refUer = userRepository.findOne(source.userId);
                    map.put("orgName", refUer.name);
                } else {
                    map.put("orgName", "--");
                }
                map.put("originalPrice", source.originalPrice);
                List<String> charges = evaluatePriceRepository
                        .findChargeByEvaluateIdAndState(source.id, LiveDieState.LIVE);
                map.put("charge", ManageUtils.getShowPrice(charges));
                return map;
            }

        }));
    }


    @ResponseBody
    @RequestMapping(path = "ref-applyStat", method = RequestMethod.GET)
    public AjaxResponse refApplyStat(@DateTimeFormat(pattern = "yyyy-MM-dd") Date beginAt,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date endAt, Long id) {
        AjaxResponse ajax = new AjaxResponse(true);
        SessionUser su = getUserInfo();
        List<Long> ids = new ArrayList<>();
        if (su.getParentId().longValue() == su.getId()) {
            ids = userRepository.findIdByParentIdAndState(su.getParentId(), LiveDieState.LIVE);
        }
        ids.add(su.getId());
        return ajax.setObj(evaluateService.listStatCount(id, ids, "BM", beginAt, endAt));
    }

    @ResponseBody
    @RequestMapping(path = "ref-applyStatCount", method = RequestMethod.GET)
    public AjaxResponse refApplyStat(Long evaluateId) {

        AjaxResponse ajax = new AjaxResponse(true);
        Date date = new Date();
        List<Long> es = Arrays.asList(evaluateId);
        SessionUser su = getUserInfo();
        Map<String, Object> map = new HashMap<>();
        List<Long> ids = new ArrayList<>();
        if (su.getParentId().longValue() == su.getId()) {
            ids = userRepository.findIdByParentIdAndState(su.getParentId(), LiveDieState.LIVE);
        }
        ids.add(su.getId());
        map.put("successCount", evaluateApplyRepository
                .countByEvaluateIdInAndReferenceIdAndVerifyInAndStateInAndDate(es, ids,
                        Arrays.asList(EvaluateVerify.Pass), Arrays.asList(EAState.LIVE), null));
        map.put("successCountDay", evaluateApplyRepository
                .countByEvaluateIdInAndReferenceIdAndVerifyInAndStateInAndDate(es, ids,
                        Arrays.asList(EvaluateVerify.Pass), Arrays.asList(EAState.LIVE), date));
        return ajax.setObj(map);
    }


    @ResponseBody
    @RequestMapping(path = "ref-applyList", method = RequestMethod.GET)
    public AjaxResponse refApplyList(Long evaluateId, String name, EvaluateVerify verify,
            EAState state, @DateTimeFormat(pattern = "yyyy-MM-dd") Date beginAt,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date endAt,
            @PageableDefault(sort = {"createdAt"}, direction = Direction.DESC) Pageable pageable) {

        AjaxResponse ajax = new AjaxResponse(true);
        SessionUser su = getUserInfo();
        List<Long> ids = new ArrayList<>();
        if (su.getParentId().longValue() == su.getId()) {
            ids = userRepository.findIdByParentIdAndState(su.getParentId(), LiveDieState.LIVE);
        }
        ids.add(su.getId());
        Page<EvaluateApply> page = evaluateApplyRepository.findEvaluateApplysAndRefIn(evaluateId,
                beginAt, endAt, name, verify, state, ids, pageable);
        return ajax.setObj(page.map(new Converter<EvaluateApply, Map<String, Object>>() {
            @Override
            public Map<String, Object> convert(EvaluateApply source) {
                Map<String, Object> map = MapUtils.convert(source);
                User user = userRepository.findOne(source.userId);
                map.put("userNumber", user.number);
                map.put("userName", user.name);
                map.put("typeDesc", source.type.desc);
                if (source.verify != null)
                    map.put("verifyDesc", source.verify.desc);
                map.put("stateDesc", source.state.desc);
                if (source.referenceId != null) {
                    User refUer = userRepository.findOne(source.referenceId);
                    map.put("refName", refUer.name);
                    UserDetail ud = userDetailRepository.findByUserId(source.referenceId);
                    map.put("refFullName", ud.realName);

                } else {
                    map.put("refName", "--");
                    map.put("refFullName", "--");
                }
                if (source.evaluatePriceId != null) {
                    EvaluatePrice ep = evaluatePriceRepository.findOne(source.evaluatePriceId);
                    map.put("epName", ep.title + "(" + ep.charge + ")");
                } else {
                    map.put("epName", "--");
                }
                if (source.type == EvaluateApplyType.TEAM) {
                    map.put("orderItemPrice",
                            evaluateApplyTeamRepository.sumMoneyByApplyId(source.id));
                } else {
                    List<Orders> os =
                            ordersRepository.findByTypeAndExtId(OrdersType.BSBM, source.id);
                    if (!os.isEmpty()) {
                        map.put("orderItemPrice", os.get(0).total);
                    }
                }
                return map;
            }
        }));
    }

    @Autowired
    private UserDetailRepository userDetailRepository;

    @RequestMapping(path = "ref-applyExportExecl", method = RequestMethod.GET)
    public void refApplyExport(Long id, @DateTimeFormat(pattern = "yyyy-MM-dd") Date beginAt,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date endAt, HttpServletResponse response)
            throws Exception {
        SessionUser su = getUserInfo();
        Evaluate evaluate = evaluateRepository.findOne(id);
        String[] lables = converLabels(evaluate.labels);
        String[] teamLables = converLabels(evaluate.teamLabels);
        String[] parentLables = converLabels(evaluate.parentInfoLabels);
        StringBuilder context = new StringBuilder(
                "报名时间,参赛编号,用户(ID),报名类型,节目,姓名,电话,组别,渠道,渠道经营者,审核状态,报名状态,付款状态,订单编号,票种,付款,备注,"
                        + (evaluate.applyGroupAdv == null ? "" : evaluate.applyGroupAdv));

        for (String lable : teamLables) {
            context.append(",").append(lable);
        }
        for (String lable : lables) {
            context.append(",").append(lable);
        }
        for (String parentLable : parentLables) {
            context.append(",").append(parentLable);
        }
        context.append("\n");
        List<EvaluateApply> evaluateApplys = evaluateApplyRepository
                .findByEvaluateIdAndNotDraftAndBeginAtDate(id, su.getId(), beginAt, endAt);

        for (EvaluateApply apply : evaluateApplys) {
            User user = userRepository.findOne(apply.userId);
            User ref = null;
            UserDetail refUd = null;
            String refName = "";
            String realName = "";
            if (apply.referenceId != null) {
                ref = userRepository.findById(apply.referenceId);
                if (ref != null) {
                    refUd = userDetailRepository.findByUserId(ref.id);
                    refName = ref.name;
                    realName = refUd.realName;
                }

            }

            PayState payState = PayState.DZF;
            Float payMoney = 0f;
            List<Orders> os = ordersRepository.findByTypeAndExtId(OrdersType.BSBM, apply.id);
            String orderNo = "--";
            if (!os.isEmpty()) {
                payState = os.get(0).payState;
                payMoney = os.get(0).total;
                orderNo = os.get(0).orderNo;
            }
            String epString = "";
            if (apply.evaluatePriceId != null) {
                EvaluatePrice ep = evaluatePriceRepository.findOne(apply.evaluatePriceId);
                if (ep != null) {
                    epString = new StringBuffer().append(ep.title).append("(").append(ep.charge)
                            .append(")").toString();
                }
            }
            context.append(DateFormatUtils.format(apply.createdAt, "yyyy.MM.dd")).append(",")
                    .append(apply.number).append(",").append(user.name + "(" + user.number + ")")
                    .append(",").append(apply.type.desc).append(",")
                    .append(apply.itemName == null ? "" : apply.fullName).append(",")
                    .append(apply.fullName == null ? "" : apply.fullName).append(",")
                    .append(apply.phone == null ? "" : apply.phone).append(",")
                    .append(apply.groupName == null ? "" : apply.groupName).append(",")
                    .append(refName).append(",").append(realName).append(",")
                    .append(apply.verify.desc).append(",").append(apply.state.desc).append(",")
                    .append(payState.desc).append(",").append(orderNo).append(",").append(epString)
                    .append(",").append(payMoney).append(",").append(apply.remark).append(",")
                    .append(apply.advName);

            coverApplyString(context, teamLables, apply.text, lables, apply.text, parentLables,
                    apply.parentText);
            context.append("\n");
            if (apply.type == EvaluateApplyType.TEAM) {
                List<EvaluateApplyTeam> eats = evaluateApplyTeamRepository
                        .findByEvaluateApplyIdAndState(apply.id, LiveDieState.LIVE);

                for (EvaluateApplyTeam eat : eats) {
                    List<Orders> teamOs =
                            ordersRepository.findByTypeAndExtId(OrdersType.TTBSBM, eat.id);
                    PayState payStateTeam = PayState.DZF;
                    Float payMoneyTeam = 0f;
                    String orderNoTeam = "--";
                    if (!teamOs.isEmpty()) {
                        payStateTeam = teamOs.get(0).payState;
                        payMoneyTeam = teamOs.get(0).total;
                        orderNoTeam = teamOs.get(0).orderNo;
                    }
                    List<EvaluateApplyTeamDetail> eatds = evaluateApplyTeamDetailRepository
                            .findByEvaluateApplyTeamIdAndState(eat.id, LiveDieState.LIVE);

                    for (int i = 0; i < eatds.size(); i++) {
                        EvaluateApplyTeamDetail eatd = eatds.get(i);
                        context.append("").append(",").append("").append(",").append("").append(",")
                                .append("团体成员").append("").append(",").append(",")
                                .append(eatd.fullName == null ? "" : eatd.fullName).append(",")
                                .append(eatd.phone == null ? "" : eatd.phone).append(",")
                                .append(eatd.groupName == null ? "" : eatd.groupName).append(",")
                                .append("").append(",").append("");;

                        if (i == 0) {
                            context.append(",").append(eat.verify.desc).append(",").append("--")
                                    .append(",").append(payStateTeam.desc).append(",")
                                    .append(orderNoTeam).append(",").append("").append(",")
                                    .append(payMoneyTeam).append(",").append("");
                        } else {
                            context.append(",").append("").append(",").append("").append(",")
                                    .append("").append(",").append(",").append("").append("")
                                    .append(",").append(payMoney).append(",").append("");
                        }
                        coverApplyString(context, teamLables, null, lables, eatd.text, parentLables,
                                null);
                        context.append("\n");
                    }
                }
            }
        }
        this.export(evaluate.title + "_报名", context.toString(), response);
    }



    @Autowired
    private EvaluateJuryRepository evaluateJuryRepository;
    @Autowired
    private JudgesService judgesService;

    @RequestMapping(path = "list-detailJury", method = RequestMethod.GET)
    public String index(Long id, ModelMap model) {
        model.put("number", judgesService.getBaseData(id));
        return "v2/evaluate/list-detailJury";
    }

    @ResponseBody
    @RequestMapping(path = "list-detailJuryList", method = RequestMethod.GET)
    public JsonResponseBean getData(Long evaluateId, String orderType,
            @PageableDefault(sort = {"createdAt"}, direction = Direction.DESC) Pageable pageable) {
        Page<EvaluateJury> page = null;
        if (StringUtils.isEmpty(orderType)) {
            page = evaluateJuryRepository.getTableData(evaluateId, pageable);
        } else if ("dp".equals(orderType)) {
            page = evaluateJuryRepository.getTableDataDesc(evaluateId, pageable);
        }
        Object obj = page.map(new Converter<EvaluateJury, Map<String, Object>>() {
            @Override
            public Map<String, Object> convert(EvaluateJury source) {
                Map<String, Object> map = MapUtils.convert(source);
                User user = userRepository.findOne(source.teacherId);
                if (user != null)
                    map.put("name", user.name);
                if (source.teacherId != null) {
                    map.put("commentNumber",
                            judgesService.getCommentNumber(evaluateId, source.teacherId));
                    map.put("postNumber",
                            judgesService.getPostNumber(evaluateId, source.teacherId));
                    map.put("scoreNumber",
                            judgesService.getScoreNumber(evaluateId, source.teacherId));
                }
                return map;
            }
        });
        return new JsonResponseBean(obj, true);
    }



    @RequestMapping(path = "list-detailJuryExportExecl", method = RequestMethod.GET)
    public void list_detailJuryExportExecl(Long id,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date beginAt,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date endAt, HttpServletResponse response)
            throws Exception {
        Evaluate evaluate = evaluateRepository.findOne(id);
        ExcelData excel = new ExcelData();
        excel.getTitles().add("姓名");
        excel.getTitles().add("用户编号");
        excel.getTitles().add("点评条数");
        excel.getTitles().add("点评贴数");
        excel.getTitles().add("打分数");
        excel.getTitles().add("备注");
        List<EvaluateJury> ejs = evaluateJuryRepository.getByEvaluateId(id);

        for (int i = 0; i < ejs.size(); i++) {

            EvaluateJury ej = ejs.get(i);
            User user = userRepository.findOne(ej.teacherId);
            excel.addRowsData("用户编号", i, user.number);
            excel.addRowsData("姓名", i, user.name);
            excel.addRowsData("点评条数", i, judgesService.getCommentNumber(id, ej.teacherId));
            excel.addRowsData("点评贴数", i, judgesService.getPostNumber(id, ej.teacherId));
            excel.addRowsData("打分数", i, judgesService.getScoreNumber(id, ej.teacherId));
            excel.addRowsData("备注", i, ej.remarks);

        }
        ExportExcelUtils.exportExcel(response, evaluate.title + "_评委", excel);
    }
}
